package com.example.quiz.controller;

import com.example.quiz.common.Result;
import com.example.quiz.model.Category;
import com.example.quiz.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/category")
public class CategoryController {

    @Autowired
    private CategoryService categoryService;

    @PostMapping
    public Result<Integer> addCategory(@RequestBody Category category) {
        int result = categoryService.add(category);
        if (result > 0) {
            return Result.success(result);
        }
        return Result.error("添加分类失败");
    }

    @DeleteMapping("/{id}")
    public Result<Integer> deleteCategory(@PathVariable Long id) {
        try {
            int result = categoryService.deleteById(id);
            if (result > 0) {
                return Result.success(result);
            }
            return Result.error("删除分类失败");
        } catch (RuntimeException e) {
            return Result.error(e.getMessage());
        }
    }

    @PutMapping
    public Result<Integer> updateCategory(@RequestBody Category category) {
        int result = categoryService.update(category);
        if (result > 0) {
            return Result.success(result);
        }
        return Result.error("更新分类失败");
    }

    @GetMapping("/{id}")
    public Result<Category> getCategory(@PathVariable Long id) {
        Category category = categoryService.getById(id);
        if (category != null) {
            return Result.success(category);
        }
        return Result.error("分类不存在");
    }

    @GetMapping("/list")
    public Result<List<Category>> getAllCategories() {
        return Result.success(categoryService.getAll());
    }

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Result<String> handleException(Exception e) {
        if (e instanceof RuntimeException) {
            return Result.error(e.getMessage());
        }
        return Result.error("系统错误，请稍后重试");
    }
}
